<template>
  <div class="login">
    <div class="login-content">
      <div class="login-form">
        <el-form ref="formRef" :model="resetData" :rules="rules">
          <div class="form-title">
            <h2>{{ $t("user.passwordReset") }}</h2>
          </div>
          <el-form-item :label="$t('user.userEmail')" prop="userEmail">
            <el-input
              ref="userEmail"
              v-model="resetData.userEmail"
              :placeholder="$t('user.emailTip')"
              name="userEmail"
            >
              <template #append>
                <el-icon :class="sendBtn" @click="sendActiveCode">{{ $t("user.sendOut") }}</el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item v-if="showPasswordInput" :label="$t('user.activeCode')" prop="activeCode">
            <el-input
              ref="activeCode"
              v-model="resetData.activeCode"
              :placeholder="$t('user.activeCode')"
              name="activeCode"
            />
          </el-form-item>
          <el-form-item
            v-if="showPasswordInput"
            :label="$t('user.userNewPassword')"
            prop="userPassword"
          >
            <el-input
              ref="userPassword"
              v-model="resetData.userPassword"
              :placeholder="$t('user.userNewPassword')"
              name="userPassword"
              type="password"
            />
          </el-form-item>
          <el-form-item
            v-if="showPasswordInput"
            :label="$t('user.confirmPassword')"
            prop="confirmPassword"
          >
            <el-input
              ref="confirmPassword"
              v-model="resetData.confirmPassword"
              :placeholder="$t('user.confirmPassword')"
              name="confirmPassword"
              type="password"
            />
          </el-form-item>
          <el-button
            v-if="showPasswordInput"
            :loading="loading"
            type="primary"
            class="w-full"
            @click.prevent="resetNewPassword"
          >
            {{ $t("user.updatePassword") }}
          </el-button>
          <router-link :to="{ name: 'Login' }">
            <p style="text-align: center">
              <e-text>{{ $t("user.remenberPassword") }},</e-text>
              <el-link type="primary">{{ $t("register.gotoLogin") }}</el-link>
            </p>
          </router-link>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { ref } from "vue";
import type { FormInstance } from "element-plus";
import UserAPI, { ResetPasswordForm } from "@/api/system/user";

const { t } = useI18n();
const router = useRouter();
const labelWidth = ref(100);
const sendBtn = ref("el-icon-email");
const showPasswordInput = ref(false);

const formRef = ref<FormInstance>();
const loading = ref(false);

const resetData = reactive<ResetPasswordForm>({
  userEmail: "",
  userPassword: "",
  confirmPassword: "",
  activeCode: "",
});

watch(
  () => resetData.userEmail,
  (val) => {
    if (val) {
      sendBtn.value = "sendBtn";
    } else {
      sendBtn.value = "";
    }
  }
);

const rules = computed(() => {
  return {
    userEmail: [
      {
        required: true,
        message: t("common.plsInput") + t("user.userEmail"),
        trigger: "blur",
      },
      {
        email: true,
        message: t("user.emailFormatError"),
        trigger: "blur",
      },
    ],
    userPassword: [
      {
        required: true,
        message: t("common.plsInput") + t("user.userNewPassword"),
        trigger: "blur",
      },
      {
        min: 6,
        max: 18,
        message: t("user.passwordLength"),
        trigger: "blur",
      },
    ],
    confirmPassword: [
      {
        required: true,
        message: t("common.plsInput") + t("user.confirmPassword"),
        trigger: "blur",
      },
      {
        min: 6,
        max: 18,
        message: t("user.passwordLength"),
        trigger: "blur",
      },
      {
        validator: (rule: any, value: string, callback: any) => {
          if (value !== resetData.userPassword) {
            callback(new Error(t("user.passwordNotSame")));
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ],
    activeCode: [
      {
        required: true,
        message: t("common.plsInput") + t("register.activeCode"),
        trigger: "blur",
      },
    ],
  };
});

function sendActiveCode() {
  if (resetData.userEmail === "") {
    ElMessage.error(t("common.plsInput") + t("user.userEmail"));
    return;
  }
  UserAPI.sendActiveCode(resetData.userEmail)
    .then((res) => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.message);
        showPasswordInput.value = true;
      } else {
        ElMessage.error(res.data.message);
      }
    })
    .finally(() => (loading.value = false));
}
// submit to register
async function resetNewPassword() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      UserAPI.resetForgotPassword(resetData)
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success(res.data.message);
            router.push({ name: "Login" });
            loading.value = false;
          } else {
            ElMessage.error(res.data.message);
          }
        })
        .finally(() => (loading.value = false));
    }
  });
}
</script>

<style lang="scss" scoped>
.sendBtn {
  color: #3b82f6;
  font-weight: bold;
  cursor: pointer;
}
.login {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  background: url("@/assets/images/login-background-light.jpg") no-repeat center right;

  .login-header {
    position: absolute;
    top: 0;
    display: flex;
    justify-content: right;
    width: 100%;
    padding: 15px;

    .logo {
      width: 26px;
      height: 26px;
    }

    .title {
      margin: auto 5px;
      font-size: 24px;
      font-weight: bold;
      color: #3b82f6;
    }
  }

  .login-content {
    display: flex;
    width: 450px;
    overflow: hidden;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: var(--el-box-shadow-light);

    @media (width <= 768px) {
      flex-direction: column;
      max-width: 100%;
      height: 100vh;
      padding: 0 30px;
      border-radius: 0;
      box-shadow: none;
    }

    .login-img {
      display: flex;
      flex: 3;
      align-items: center;
      justify-content: center;
      background: linear-gradient(60deg, #165dff, #6aa1ff);

      @media (width <= 768px) {
        display: none;
      }
    }

    .login-form {
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding: 30px;

      @media (width <= 768px) {
        width: 100%;
        padding: 0 20px;
      }

      .form-title {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 0 20px;
        text-align: center;
      }

      .input-wrapper {
        display: flex;
        align-items: center;
        width: 100%;
      }

      .captcha-img {
        height: 48px;
        cursor: pointer;
        border-top-right-radius: 6px;
        border-bottom-right-radius: 6px;
      }

      .third-party-login {
        display: flex;
        justify-content: center;
        width: 100%;
        color: var(--el-text-color-secondary);

        *:not(:first-child) {
          margin-left: 20px;
        }

        .icon {
          cursor: pointer;
        }
      }
    }
  }

  .login-footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    text-align: center;
  }
}
</style>
